
#include <iomanip>
#include <boost/property_tree/ptree.hpp>
#include "core/modules.h"
#include "core/dest_cache.h"
#include "core/threadpool.h"
#include "core/service.h"
#include "core/core_error.h"
#include "config.h"

void StartPreloadModules(void) {
  using boost::property_tree::ptree;
  ptree& preload = Config::GetTree().get_child("server.preload_modules");
  for (const ptree::value_type& v : preload) {
    const ptree& module = v.second;
    auto name = module.get_optional<std::string>("name");
    std::string module_name = module.get<std::string>("soname");
    auto args = module.get_optional<std::string>("args");
    Handle h = Services::Instance().New((name ? (*name).c_str() : NULL),
                                        module_name.c_str(),
                                        (args ? (*args).c_str() : NULL));
    LOG(INFO) << "service [" << (name ? (*name).c_str() : "NULL")
              << ":" << std::hex << h.value() << "] UP";
  }
}

int main(int argc, char** argv) {
  try {
    google::InitGoogleLogging(argv[0]);
    Config::Init(argv[1]);
    Services::Instance().Init();
    DestCache::Instance().Init();
    StartPreloadModules();
    ThreadPool::Instance().Run();
  } catch(std::exception& e) {
    std::cout << e.what() << std::endl;
  }
  return 0;
}

